package com.yupi.usercenter.job;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.model.domain.enity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 缓存预热
 *
 * @author ZhengT
 */
@Component
@Slf4j
public class PreCacheJob {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private UserMapper userMapper;

    private static final String RECOMMAND_PREFIX = "FRIEND:RECOMMAND:";

    //热点用户,这里可以根据自己的业务情况进行调整
    List<Long> userIds = Arrays.asList(1L);

    //TODO 这里后续需要添加热点数据的探查从而预热热点数据
    @Scheduled(cron = "0 0 0/3 * * ? ")
    public void preCache(){
        Page<User> userPage = userMapper.selectPage(new Page<>(1, 10), null);
        for (Long userId : userIds){
            try {
                redisTemplate.opsForValue().set(RECOMMAND_PREFIX + userId, userPage);
            } catch (Exception e) {
                log.error("缓存预热失败", e);
            }
        }
    }
}
